<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Console\Commands\WdtClient;
use Illuminate\Support\Str;

/**
 * 批量推送组合商品到旺店通ERP 5min 组合商品
 * 执行命令：php artisan sync:SuitesPush
 * 文档：https://open.wangdian.cn/qyb/open/apidoc/doc?path=suites_push.php
 */
class SyncSuitesPush extends Command
{
    protected $signature = 'sync:SuitesPush';
    protected $description = '批量推送组合商品到旺店通ERP';

    public function handle()
    {
        Log::info('同步任务SyncSuitesPush', ['开始推送组合商品到旺店通']);
        $sid = config('services.wdt.sid');
        $appkey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'suites_push.php';

        $c = new WdtClient($sid, $appkey, $secret, $url);

        // 查询所有上架的组合商品
        $groupGoods = DB::table('goods')->where(['status' => 1, 'is_group' => 1])->get();
        $total = $groupGoods->count();
        $this->info('组合商品总数: ' . $total);

        if ($total == 0) {
            $this->info('没有需要推送的组合商品');
            return;
        }

        $batchSize = 20; // 每批处理的数量
        $groupGoodsArr = $groupGoods->toArray();
        $batches = array_chunk($groupGoodsArr, $batchSize);

        foreach ($batches as $batch) {
            $suiteInfoArr = [];

            foreach ($batch as $good) {
                // 解析组合商品的组成部分
                $goodsGroup = json_decode($good->goods_group, true);
                if (empty($goodsGroup)) {
                    Log::warning('组合商品数据异常', ['goods_id' => $good->id, 'goods_sn' => $good->goods_sn]);
                    continue;
                }

                // 准备组合商品明细
                $suiteDetails = [];
                $isDefaultRatio = 1; // 你可以根据实际情况设置

                foreach ($goodsGroup as $item) {
                    // 获取子商品ID
                    $subGoodId = $item['id'] ?? null;
                    $number = $item['number'] ?? 1;
                    
                    if (!$subGoodId) {
                        Log::warning('组合商品明细缺少商品ID', ['parent_goods_sn' => $good->goods_sn]);
                        continue;
                    }
                    
                    // 查询子商品信息
                    $subGood = DB::table('goods')
                        ->where('id', $subGoodId)
                        ->where('status', 1)
                        ->first();

                    if (!$subGood) {
                        Log::warning('组合商品中的子商品不存在或已下架', [
                            'parent_goods_sn' => $good->goods_sn,
                            'sub_goods_id' => $subGoodId
                        ]);
                        continue;
                    }

                    // 组装规格编码
                    $specNo = $subGood->goods_sn . "_" . $subGood->goods_unit . "_" . $subGood->goods_specification;

                    $detail = [
                        'spec_no' => $specNo,
                        'num' => $number,
                        'is_fixed_price' => 0,
                    ];
                    // 只有在 is_default_ratio=0 时才传 ratio
                    if ($isDefaultRatio == 0) {
                        $detail['ratio'] = 0; // 这里要按实际比例赋值
                    }
                    $suiteDetails[] = $detail;
                }

                if (empty($suiteDetails)) {
                    Log::warning('组合商品没有有效的子商品', ['goods_id' => $good->id, 'goods_sn' => $good->goods_sn]);
                    continue;
                }

                // 组装组合商品信息
                $suiteInfoArr[] = [
                    'suite_name' => $good->goods_name,
                    'suite_no' => $good->goods_sn,
                    'is_default_ratio' => $isDefaultRatio,
                    'short_name' => $good->goods_name,
                    'barcode' => $good->goods_barcode ?: $good->goods_sn,
                    'brand_no' => $good->goods_supplier,
                    'class_name' => (string)$good->goods_type,
                    'unit_name' => $good->goods_unit,
                    'retail_price' => $good->goods_price,
                    'wholesale_price' => $good->goods_price, // 批发价与零售价一致
                    'remark' => $good->goods_remark,
                    'is_print_suite' => 1, // 组合装以及明细
                    'large_split' => 0, // 默认非大件
                    'suite_details' => $suiteDetails
                ];
            }

            if (empty($suiteInfoArr)) {
                continue;
            }

            // 小驼峰转下划线（旺店通接口要求参数为下划线风格）
            $suiteInfoArrSnake = array_map(function ($item) {
                $itemSnake = [];
                foreach ($item as $k => $v) {
                    $itemSnake[Str::snake($k)] = $v;
                }
                // suite_details 也要转
                if (isset($itemSnake['suite_details'])) {
                    $itemSnake['suite_details'] = array_map(function ($detail) {
                        $detailSnake = [];
                        foreach ($detail as $dk => $dv) {
                            $detailSnake[Str::snake($dk)] = $dv;
                        }
                        return $detailSnake;
                    }, $itemSnake['suite_details']);
                }
                return $itemSnake;
            }, $suiteInfoArr);

            $suiteInfoJson = json_encode($suiteInfoArrSnake, JSON_UNESCAPED_UNICODE);
            $c->putApiParam('suite_info', $suiteInfoJson);

            Log::info('推送旺店通组合商品参数', ['suite_info' => $suiteInfoJson]);
            $result = $c->wdtOpenApi();
            Log::info('旺店通组合商品推送结果', [$result]);
            $this->info('旺店通组合商品推送结果: ' . $result);

            // 解析结果，更新商品表中的ERP信息
            $resultData = json_decode($result, true);
            if (isset($resultData['code']) && $resultData['code'] == 0) {
                $this->info('成功推送组合商品数: ' . ($resultData['new_count'] + $resultData['chg_count']));

                // 更新商品表中的ERP相关字段
                foreach ($batch as $good) {
                    if (isset($good->id)) {
                        DB::table('goods')->where('id', $good->id)->update([
                            'erp_spec_type' => 2, // 2表示组合装
                            'updated_at' => time()
                        ]);
                    }
                }
            } else {
                $this->error('推送失败: ' . ($resultData['error_message'] ?? '未知错误'));
            }
        }

        $this->info('组合商品推送任务执行完毕');
    }
}